package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.common.utils.JwtConstants.*;


@Service
public class UserAuthServiceImpl implements UserAuthService {


    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param response 返回客户端数据
     */
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        //校验用户名 密码
        UserDTO userDTO = null;
        try {
            //调用用户微服务中暴露的方法
            userDTO = userClient.queryUserByUserNameAndPassword(username, password);
        } catch (FeignException e) {
            if (e.status()==400){
                // 抛出远程调用异常转换
                throw new LyException(e.status(), e.contentUTF8());
            }
            throw new LyException(500,"验证用户信息失败！",e);
        }
        if (userDTO == null){
            throw new LyException(400, "用户名或密码错误！");
        }

        //生成jwt
        UserDetails userDetails = UserDetails.of(userDTO.getId(), userDTO.getUsername());
        String jwt = jwtUtils.createJwt(userDetails);


        //写入cookie
        createCookie(response,jwt);

    }

    //生成cookie
    private void createCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        cookie.setPath(COOKIE_PATH);  //作用与所有的请求
        cookie.setDomain(COOKIE_DOMAIN);  // cookie的作用域
        cookie.setHttpOnly(true);// 是否禁止JS操作cookie，避免XSS攻击
        cookie.setMaxAge(COOKIE_MaxAge);// cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        response.addCookie(cookie);
    }

    /**
     * 退出登录
     * @param request 请求参数
     * @param response 响应数据，写cookie用
     * @return 无
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {

        //获取用户cookie
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if (jwt == null){
            //用户未登录
            return;
        }
        //校验cookie中的token
        try {
            Payload payload = jwtUtils.parseJwt(jwt);

            //删除redis
            jwtUtils.deleteRedisJwt(payload.getUserDetail().getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //删除cookie  （重新写一个cookie，maxAge为0）
        CookieUtils.deleteCookie(COOKIE_NAME,COOKIE_DOMAIN,response);
    }


}
